/*
 * Copyright 2010 - Jeremie Brebec
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package org.jb.sharedbills.shared.model;

import org.jb.sharedbills.shared.model.notification.AbstractNotifier;
import org.jb.sharedbills.shared.model.notification.Notification;
import org.jb.sharedbills.shared.model.notification.NotificationListener;
import org.jb.sharedbills.shared.model.notification.ObservableCollection;
import org.jb.sharedbills.shared.model.notification.ObservableList;

/**
 * 
 * @author jeremie
 *
 */
//@Embeddable
public class Group extends AbstractNotifier {

	/**
	 * 
	 */
	private static final long serialVersionUID = 188931073989096619L;

	public enum Kind {
		ALL_MEMBERS,
		MEMBER_TO_MEMBER,
		CUSTOM
	};
	
	private ObservableList<Member> members = new ObservableList<Member>( this, "members" );
	private String name;
	private Kind kind = Kind.CUSTOM;
	private transient boolean members_registered = false;
	
	/**
	 * 
	 */
	public Group() {
	}
	
	/**
	 * 
	 * @param name
	 * @param members
	 */
	public Group(String name, Member... members ) {
		setName( name );
		for( Member m : members ) {
			this.members.add( m );
		}
	}
	
	/**
	 * 
	 * @param kind
	 */
	public void setKind( Kind kind ) {
		this.kind = kind;
	}
	
	/*
	 * 
	 */
	public Kind getKind() {
		return kind;
	}
	
	/**
	 * 
	 * @param name
	 */
	public void setName(String name) {
		if (this.name == null || !this.name.equals(name)) {
			String oldName = this.name;
			this.name = name;
			doNotify( "name", oldName, this.name );
		}
		this.name = name;
	}
	
	/**
	 * 
	 * @return
	 */
	public String getName() {
		return name;
	}
	
	/**
	 * 
	 * @return
	 */
	public ObservableCollection<Member> getMembers() {
		return members;
	}

	@Override
	public void handle(Notification notification) {
		if (notification.getSender() instanceof Member && notification.getProperty().equals("name")) {
			doNotify("members_name", null, null);
		}
		super.handle(notification);
	}

	@Override
	public void addListener(NotificationListener listener) {
		if (!members_registered) {
			members_registered=true;
			members.addListener(this);
		}
		super.addListener(listener);
	}
	
	
	
	
}
